import { FC, useState } from 'react';
import { Card, Tabs, Form, Input, Button, Table, message, Tag } from 'antd';
import { LockOutlined, MailOutlined, DownloadOutlined } from '@ant-design/icons';
import * as XLSX from 'xlsx';
import MainLayout from '../../components/MainLayout';
import type { TabsProps } from 'antd';
import styles from './Profile.module.css';
import type { ColumnsType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';

interface OperationRecord {
  key: string;
  time: string;
  type: string;
  operation: string;
  status: 'success' | 'error' | 'warning';
}

const Profile: FC = () => {
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const handlePasswordChange = async (values: any) => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      message.success('密码修改成功');
    } catch (error) {
      message.error('修改失败');
    } finally {
      setLoading(false);
    }
  };

  const handleEmailChange = async (values: any) => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      message.success('邮箱修改成功');
    } catch (error) {
      message.error('修改失败');
    } finally {
      setLoading(false);
    }
  };

  const columns: ColumnsType<OperationRecord> = [
    {
      title: '操作时间',
      dataIndex: 'time',
      key: 'time',
      width: 180,
      render: (text) => <span className={styles.timeColumn}>{text}</span>
    },
    {
      title: '操作类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (text) => (
        <Tag color="blue" className={styles.typeTag}>
          {text}
        </Tag>
      )
    },
    {
      title: '操作内容',
      dataIndex: 'operation',
      key: 'operation',
      render: (text) => <span className={styles.operationColumn}>{text}</span>
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: 'success' | 'error' | 'warning') => {
        const statusConfig = {
          success: { color: 'success', text: '成功' },
          error: { color: 'error', text: '失败' },
          warning: { color: 'warning', text: '处理中' }
        } as const;
        
        return (
          <Tag color={statusConfig[status].color}>
            {statusConfig[status].text}
          </Tag>
        );
      }
    }
  ];

  // 处理表格选择
  const rowSelection: TableRowSelection<OperationRecord> = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    }
  };

  // 导出选中记录到Excel
  const handleExport = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要导出的记录');
      return;
    }

    try {
      // 模拟数据，实际项目中应该从 dataSource 中过滤
      const dataSource = [
        {
          key: '1',
          time: '2024-03-20 10:30:45',
          type: '文档编辑',
          operation: '修改了《2024年第一季度工作报告》',
          status: 'success',
        },
        // ... 其他数据
      ];

      // 过滤选中的数据
      const exportData = dataSource.filter(item => 
        selectedRowKeys.includes(item.key)
      ).map(item => ({
        '操作时间': item.time,
        '操作类型': item.type,
        '操作内容': item.operation,
        '状态': item.status === 'success' ? '成功' : 
               item.status === 'error' ? '失败' : '处理中'
      }));

      // 创建工作簿
      const wb = XLSX.utils.book_new();
      const ws = XLSX.utils.json_to_sheet(exportData);

      // 添加工作表到工作簿
      XLSX.utils.book_append_sheet(wb, ws, '操作记录');

      // 导出文件
      XLSX.writeFile(wb, '操作记录.xlsx');
      message.success('导出成功');
    } catch (error) {
      message.error('导出失败');
    }
  };

  const items: TabsProps['items'] = [
    {
      key: 'basic',
      label: '基本信息',
      children: (
        <div className={styles.formContainer}>
          <Form layout="vertical" onFinish={handleEmailChange}>
            <Form.Item
              name="email"
              label="邮箱"
              rules={[
                { required: true, message: '请输入邮箱' },
                { type: 'email', message: '请输入有效的邮箱地址' }
              ]}
            >
              <Input prefix={<MailOutlined />} placeholder="请输入新邮箱" />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" loading={loading}>
                修改邮箱
              </Button>
            </Form.Item>
          </Form>

          <Form layout="vertical" onFinish={handlePasswordChange}>
            <Form.Item
              name="oldPassword"
              label="原密码"
              rules={[{ required: true, message: '请输入原密码' }]}
            >
              <Input.Password prefix={<LockOutlined />} placeholder="请输入原密码" />
            </Form.Item>
            <Form.Item
              name="newPassword"
              label="新密码"
              rules={[{ required: true, message: '请输入新密码' }]}
            >
              <Input.Password prefix={<LockOutlined />} placeholder="请输入新密码" />
            </Form.Item>
            <Form.Item
              name="confirmPassword"
              label="确认密码"
              dependencies={['newPassword']}
              rules={[
                { required: true, message: '请确认新密码' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('newPassword') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致'));
                  },
                }),
              ]}
            >
              <Input.Password prefix={<LockOutlined />} placeholder="请确认新密码" />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" loading={loading}>
                修改密码
              </Button>
            </Form.Item>
          </Form>
        </div>
      ),
    },
    {
      key: 'logs',
      label: '操作记录',
      children: (
        <div className={styles.container}>
          <Card 
            title="操作记录" 
            className={styles.recordCard}
            extra={
              <div className={styles.cardExtra}>
                <Button 
                  type="primary" 
                  icon={<DownloadOutlined />}
                  onClick={handleExport}
                  disabled={selectedRowKeys.length === 0}
                >
                  导出所选记录
                </Button>
              </div>
            }
          >
            <Table<OperationRecord>
              rowSelection={rowSelection}
              columns={columns}
              dataSource={[
                {
                  key: '1',
                  time: '2024-03-20 10:30:45',
                  type: '文档编辑',
                  operation: '修改了《2024年第一季度工作报告》',
                  status: 'success',
                },
                // ... 其他数据
              ]}
              pagination={{
                pageSize: 10,
                showTotal: (total) => `共 ${total} 条记录`,
                showQuickJumper: true
              }}
              className={styles.table}
            />
          </Card>
        </div>
      ),
    },
  ];

  return (
    <MainLayout>
      <Card title="个人中心" className={styles.profileCard}>
        <Tabs items={items} />
      </Card>
    </MainLayout>
  );
};

export default Profile; 